import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import router from '@/router'
// create an axios instance
// 创建实例
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  // baseURL: 'http://ihrm-java.itheima.net', // 设置基地址
  timeout: 5000 // request timeout
})

// 请求拦截器
service.interceptors.request.use(config => {
  // console.log(config) 是一个对象 里面有headers属性
  const token = store.state.user.token
  if (token) {
    config.headers['Authorization'] = `Bearer ${token}`
  }
  return config
},
error => {
  // do something with request error
  // console.log(error) // for debug
  return Promise.reject(error)
}
)

// 响应拦截器
service.interceptors.response.use(response => {
  // response 是axios返回来的数据
  // console.log(response)
  // 判断用户名/密码是否错误
  if (response.data.success) {
    return response.data
  } else {
    Message({
      message: response.data.message,
      type: 'error'
    })
    return Promise.reject(new Error(response.data.message))
  }
},
// 网络错误会走这个error
async error => {
  // console.dir(error)
  if (error.response && error.response.data && error.response.data.code === 10002) {
    // 调用退出接口
    await store.dispatch('user/useLoginOut')
    router.push('/login')
    return Message({
      message: '请求超时,请重新登陆',
      type: 'error'
    })
  }
  Message({
    message: error.message,
    type: 'error'
  })
  return Promise.reject(error)
}
)

export default service

// // request interceptor 请求拦截器
// service.interceptors.request.use(
//   config => {
//     // do something before request is sent

//     if (store.getters.token) {
//       // let each request carry token
//       // ['X-Token'] is a custom headers key
//       // please modify it according to the actual situation
//       config.headers['X-Token'] = getToken()
//     }
//     return config
//   },
//   error => {
//     // do something with request error
//     console.log(error) // for debug
//     return Promise.reject(error)
//   }
// )

// // response interceptor 相应拦截器
// service.interceptors.response.use(
//   /**
//    * If you want to get http information such as headers or status
//    * Please return  response => response
//   */

//   /**
//    * Determine the request status by custom code
//    * Here is just an example
//    * You can also judge the status by HTTP Status Code
//    */
//   response => {
//     const res = response.data

//     // if the custom code is not 20000, it is judged as an error.
//     return res
//   },
//   error => {
//     console.log('err' + error) // for debug
//     Message({
//       message: error.message,
//       type: 'error',
//       duration: 5 * 1000
//     })
//     return Promise.reject(error)
//   }
// )
